package com.acceptable.qucun.generic.security;

import com.acceptable.qucun.generic.util.CodeUtil;
import com.acceptable.qucun.user.service.LoginVerifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class LoginAuthenProvider implements AuthenticationProvider {
    @Autowired private LoginVerifyService loginVerify;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String username = (String) authentication.getPrincipal();
        String password = CodeUtil.base64Encode((String) authentication.getCredentials());

        // 验证账户是否存在
        UserDetails userInfo = loginVerify.loadUserByUsername(username);

//        System.out.println("com.acceptable.web.qucun.other.security.LoginAuthenProvider");
        // 验证密码
        if(!loginVerify.getEncoder().matches(password, userInfo.getPassword())) {
            throw new BadCredentialsException("密码或用户名错误");
        }

//        System.out.println("com.acceptable.web.qucun.other.security.LoginAuthenProvider 返回前");
        // 前后端分离情况下 处理逻辑...
        // 更新登录令牌 - 之后访问系统其它接口直接通过token认证用户权限...
        return new UsernamePasswordAuthenticationToken(userInfo, password, userInfo.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
